/**
 * Created by chen on 18/5/22.
 */
window.onload = function(){
  var allCartList = JSON.parse(localStorage.getItem("cartList"))||[];
  getCartNum(allCartList);
  getTmplShowInView(allCartList);
  var total = getSumTotal(allCartList);
  $("#pay_total").text(total);
};
var promotion_barcodes = ['ITEM00001','ITEM00006'];//优惠促销barcode 买二送一
function getAllCartList(allCartList)
{
  for(var i = 0; i < allCartList.length; i ++)
  {
    var item_info = allCartList[i];
    var barcode = _.find(promotion_barcodes,function(barcode){
      return barcode == item_info.barcode;
    });
    if (barcode == undefined || item_info.count < 3)
    {
      item_info.subtotal = item_info.price * item_info.count + "元";
    }
    else
    {
      item_info.subtotal = item_info.price * (item_info.count - Math.floor(item_info.count/3))+"元（原价："
        +item_info.price * item_info.count + "元）";
    }
  }
  return allCartList;
}
function getSumTotal(allCartList)
{
  var sum = 0;
  for(var i = 0; i < allCartList.length; i ++)
  {
    sum += allCartList[i].count * allCartList[i].price;
  }
  return sum.toFixed(2);
}

function subItemFromCart(){
  var allCartList = JSON.parse(localStorage.getItem("cartList"))||[];
  var id=$("#"+event.target.id)[0].id;
  id = id.substr(3);
  var find_item = _.find(allCartList, function(item){
    return id == item.barcode;
  });
  find_item.count --;
  if (find_item.count == 0)
  {
    //删除一条信息；
    allCartList.remove(find_item.barcode);
  }
  getCartNum(allCartList);
  getTmplShowInView(allCartList);
  var total = getSumTotal(allCartList);
  $("#pay_total").text(total);
  localStorage.setItem("cartList",JSON.stringify(allCartList));
}

function addItemToCart(){
  var allCartList = JSON.parse(localStorage.getItem("cartList"))||[];
  var id=$("#"+event.target.id)[0].id;
  id = id.substr(3);
  var find_item = _.find(allCartList, function(item){
    return id == item.barcode;
  });
  find_item.count ++;
  getCartNum(allCartList);
  getTmplShowInView(allCartList);
  var total = getSumTotal(allCartList);
  $("#pay_total").text(total);
  localStorage.setItem("cartList",JSON.stringify(allCartList));
}

function getTmplShowInView(allCartList)
{
  var cart_list = {list : getAllCartList(allCartList)};
  var tpl = document.getElementById('cartTpl').innerHTML;
  document.getElementById('cart_list_info').innerHTML = template(tpl, cart_list);
}


Array.prototype.indexOf = function(val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i].barcode == val) return i;
  }
  return -1;
};
Array.prototype.remove = function(val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

function pay(){
  window.location.href = "pay.html"
}